package com.luokangtao.user.service;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.luokangtao.common.entity.PageResult;
import com.luokangtao.common.handler.BaseException;
import com.luokangtao.common.util.IdWorker;
import com.luokangtao.common.util.MD5Util;
import com.luokangtao.user.dto.UserQueryCondition;
import com.luokangtao.user.entity.User;
import com.luokangtao.user.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.time.LocalDateTime;
import java.util.List;

/**
 * 用户业务层
 * @author luokangtao
 * @create 2019-07-22 20:34
 */
@Service
@Slf4j
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private IdWorker idWorker;

    /**
     * 分页查询
     * @return
     */
    public  PageResult findAll(UserQueryCondition userQueryCondition) {
        //组装分页数据
        Page page =new Page(userQueryCondition.getCurrent(),userQueryCondition.getSize());
        //创建查询条件
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        IPage<User> userIPage = userMapper.selectPage(page, queryWrapper);
        //组装数据
        return new PageResult(userIPage.getCurrent(),userIPage.getSize(),userIPage.getTotal(),userIPage.getRecords());
    }

    /**
     * 创建一个用户
     * @param user
     * @return
     */
    public String add(User user) {
        //获取分布式id
        user.setId(idWorker.nextId()+"");
        user.setCreateTime(LocalDateTime.now());//创建时间
        user.setStatus("1");//用户状态 0:禁用 1:启用

        //密码加密: md5+
        String encryptedPwd =null;
        try {
            encryptedPwd = MD5Util.getEncryptedPwd(user.getPassword());
        } catch (Exception e) {
           throw new BaseException("密码异常");
        }
        user.setPassword(encryptedPwd);
        int insert = userMapper.insert(user);
        if(insert>0){
            return "创建成功";
        }
        return "创建失败";
    }

    /**
     * 根据id查询用户
     * @param id
     * @return
     */
    public User findByOne(String id) {
        User user = userMapper.selectById(id);
        return user;
    }

}
